<template>
  <div class="left-menu-bar">
    <!-- Logo -->
    <div class="logo-container">
      <div class="logo">
        <img src="/logo.png" alt="Logo" class="logo-img" />
      </div>
    </div>
    
    <div 
      class="menu-item" 
      :class="{ active: activeMenu === 'recent', 'menu-item-clicking': clickingItem === 'recent' }" 
      @mousedown="clickingItem = 'recent'"
      @mouseup="clickingItem = null"
      @mouseleave="clickingItem = null"
      @click="$emit('menu-change', 'recent')"
    >
      <q-icon name="chat" size="24px" />
      <span class="menu-label">聊天</span>
    </div>
    <div 
      class="menu-item" 
      :class="{ active: activeMenu === 'friends', 'menu-item-clicking': clickingItem === 'friends' }" 
      @mousedown="clickingItem = 'friends'"
      @mouseup="clickingItem = null"
      @mouseleave="clickingItem = null"
      @click="$emit('menu-change', 'friends')"
    >
      <q-icon name="people" size="24px" />
      <span class="menu-label">好友</span>
    </div>
    <div class="menu-bottom">
      <div 
        id="avatar-button"
        class="menu-item menu-avatar" 
        ref="avatarButtonRef" 
        @click.stop="handleAvatarClick"
      >
        <q-avatar class="user-avatar" size="48px">
          <img v-if="avatarUrl" :src="avatarUrl" />
          <div 
            v-else 
            class="avatar-placeholder"
            :style="getAvatarStyle(currentUser?.open_id || currentUser?.id || currentUser?.name)"
          >
            {{ currentUser?.name?.[0]?.toUpperCase() || 'U' }}
          </div>
        </q-avatar>
      </div>
      <UserMenu
        v-model="showUserMenu"
        :current-user="currentUser"
        target-selector="#avatar-button"
        @profile="$emit('profile')"
        @help="$emit('help')"
        @logout="$emit('logout')"
        @close="showUserMenu = false"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, nextTick, watch } from 'vue'
import type { User } from '../services/auth'
import UserMenu from './UserMenu.vue'
import { API_BASE_URL } from '@/config/env'
import { getAvatarStyle } from '@/utils/avatar'
import { getCachedImageUrl } from '@/services/image-cache'

const props = defineProps<{
  currentUser: User | null
  activeMenu: 'recent' | 'friends'
}>()

defineEmits<{
  'menu-change': [menu: 'recent' | 'friends']
  'profile': []
  'help': []
  'logout': []
}>()

const avatarButtonRef = ref<HTMLElement | null>(null)
const showUserMenu = ref(false)
const avatarUrl = ref<string | null>(null)
const clickingItem = ref<'recent' | 'friends' | null>(null)

// 点击头像时切换菜单显示
const handleAvatarClick = async (event: Event) => {
  // 阻止事件冒泡
  event.stopPropagation()
  event.preventDefault()
  
  // 如果菜单已经显示，则关闭
  if (showUserMenu.value) {
    showUserMenu.value = false
    return
  }
  
  // 确保 ref 已经赋值
  await nextTick()
  const targetElement = avatarButtonRef.value || document.getElementById('avatar-button')
  
  if (targetElement) {
    // 直接设置为 true，让菜单显示
    showUserMenu.value = true
  } else {
    console.warn('头像按钮引用未找到')
  }
}

defineExpose({
  avatarButtonRef
})

// 加载头像（使用缓存服务）
const loadAvatar = async () => {
  if (props.currentUser?.file_name) {
    try {
      const url = `${API_BASE_URL}/api/upload/${props.currentUser.file_name}`
      const cachedUrl = await getCachedImageUrl(url)
      avatarUrl.value = cachedUrl
    } catch (error) {
      console.error('加载头像失败:', error)
      avatarUrl.value = null
    }
  } else {
    avatarUrl.value = null
  }
}

// 监听 currentUser 变化，重新加载头像
watch(() => props.currentUser?.file_name, () => {
  loadAvatar()
}, { immediate: true })
</script>

<style lang="sass" scoped>
.left-menu-bar
  width: 80px
  background: #F7F7F7
  border-right: 1px solid #E5E5E5
  display: flex
  flex-direction: column
  align-items: center
  padding: 12px 0
  gap: 8px
  position: relative
  z-index: 1

.logo-container
  width: 100%
  padding: 12px 6px
  display: flex
  justify-content: center
  align-items: center
  border-bottom: 0.5px solid rgba(0, 0, 0, 0.08)
  margin-bottom: 8px

.logo
  width: 50px
  height: 60px
  display: flex
  align-items: center
  justify-content: center
  background: transparent
  border-radius: 6px
  transition: all 0.2s ease
  overflow: hidden
  cursor: pointer
  border: none

  &:hover
    background: rgba(0, 0, 0, 0.04)

  .logo-img
    width: 100%
    height: 100%
    object-fit: cover
    display: block
    transition: transform 0.3s ease

  &:hover .logo-img
    transform: scale(1.05)

.menu-item
  width: 48px
  height: 48px
  display: flex
  flex-direction: column
  align-items: center
  justify-content: center
  cursor: pointer
  border-radius: 8px
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1)
  color: #8E8E93
  position: relative
  -webkit-tap-highlight-color: transparent
  user-select: none

  &:hover
    background: rgba(0, 0, 0, 0.04)
    color: #191919

  // 只在真正点击菜单项时才显示 :active 效果
  // 通过 JavaScript 控制，避免在点击其他区域时被触发
  &.menu-item-clicking
    background: rgba(0, 0, 0, 0.08) !important
    color: #191919 !important

  &.active
    background: rgba(7, 193, 96, 0.08)
    color: #07C160
    position: relative
    
    // 左侧绿色指示条（参考微信风格）
    &::before
      content: ''
      position: absolute
      left: 0
      top: 50%
      transform: translateY(-50%)
      width: 3px
      height: 32px
      background: #07C160
      border-radius: 0 2px 2px 0
    
    &:hover
      background: rgba(7, 193, 96, 0.12)
      color: #06AD56
    
    &.menu-item-clicking
      background: rgba(7, 193, 96, 0.15) !important
      color: #06AD56 !important

  .menu-label
    font-size: 10px
    margin-top: 4px
    font-weight: 400
    letter-spacing: 0.1px
    transition: color 0.2s ease

.menu-bottom
  margin-top: auto
  display: flex
  flex-direction: column
  gap: 8px
  width: 100%
  align-items: center

.menu-avatar
  width: 48px
  height: 48px
  padding: 2px

  &:hover
    background: rgba(0, 0, 0, 0.04)

.user-avatar
  cursor: pointer
  border: 1px solid rgba(0, 0, 0, 0.1)
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1)

  &:hover
    border-color: rgba(0, 0, 0, 0.2)
    transform: scale(1.05)

.avatar-placeholder
  width: 100%
  height: 100%
  display: flex
  align-items: center
  justify-content: center
  color: white
  font-weight: 500
  font-size: 18px
  border: 1px solid #E5E5E5
</style>

